//
//  KINGPhotoBrowserCell.swift
//  肉荣微博
//
//  Created by king on 15/8/8.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit

/// KINGPhotoBrowserCellDelegate
protocol KINGPhotoBrowserCellDelegate:NSObjectProtocol {
    func photoBrowserCellZoom(scale:CGFloat)
    func photoBrowserCellEndZoom()
}

class KINGPhotoBrowserCell: UICollectionViewCell {
    //声明代理属性
    weak var photoDelegate:KINGPhotoBrowserCellDelegate?
    var url:NSURL?{
        didSet{
            //解决cell重用问题导致的有图片切换的效果
            imageView.image = nil
            //恢复Scroll上下文
            resetScrollContext()
            //开始转菊花
            indicator.startAnimating()
            imageView.sd_setImageWithURL(url) { (image, error, _, _) -> Void in
                //加载完成关闭菊花
                self.indicator.stopAnimating()
                if image == nil {
                    print("图片下载错误")
                }
                //self.imageView.sizeToFit()
                self.setupImageViewPostion()
            }
        }
    }
    //解决图片方法之后，切换到其他控制器中，造成图片跑出外面问题。
    private func resetScrollContext() {
        //重新设置imageView的形变,解决放大之后，重用之后不能正常显示的问题
        imageView.transform = CGAffineTransformIdentity
        
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    //根据scrollView的宽度，修改图片的尺寸
    private func displaySize(image:UIImage) -> CGSize {
//        let scale = scrollView.bounds.width / image.size.width
        let scale = UIScreen.mainScreen().bounds.width / image.size.width
        let height = image.size.height * scale
        return CGSize(width: UIScreen.mainScreen().bounds.width, height: height)
    }
    //根据图片的大小，设置ImageView的位置，如果是长图，则设置从头显示，如果是短图，在中间显示
    private func setupImageViewPostion() {
        let size = displaySize(imageView.image!)	
        if size.height < UIScreen.mainScreen().bounds.height {
            let y = (UIScreen.mainScreen().bounds.height - size.height) * 0.5
            imageView.frame = CGRect(origin: CGPointZero, size: size)
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
        } else {
            imageView.frame = CGRect(origin: CGPointZero, size: size)
            scrollView.contentSize = size
        }
    }
    
    //这里必须要重写initWithFrame，否则有病
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //contentView.backgroundColor = UIColor.randomColor()
        //添加视图
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        //设置布局
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sv]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv":scrollView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv":scrollView]))
        //布局菊花
        contentView.addSubview(indicator)
        indicator.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: -10))
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: -10))
        //配置scroll视图
        prepareScrollView()
    }
    //设置缩放比例
    private func prepareScrollView() {
        scrollView.maximumZoomScale = 2.0
        scrollView.minimumZoomScale = 0.5
        //仅仅设置缩放比例还是不够的，还要设置代理
        scrollView.delegate = self
    }
    

    //MARK: - 懒加载控件
    private lazy var scrollView = UIScrollView()
    lazy var imageView = UIImageView()
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
}

extension KINGPhotoBrowserCell:UIScrollViewDelegate {
    //重写此代理方法，告诉应用程序需要缩放那个控件
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    //当视图结束缩放之后，设置一下视图的位置
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        //进行一次过滤，如果小于0.8说明缩放之后就退出了，所以不需要设置中心位置
        if scale >= 0.8 {
            var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
            var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
            offsetX = offsetX > 0 ? offsetX : 0
            offsetY = offsetY > 0 ? offsetY : 0
            scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
        }
        //通知控制器，缩放完成
        photoDelegate?.photoBrowserCellEndZoom()
    }
    //只要一缩放就会调用这个方法
    func scrollViewDidZoom(scrollView: UIScrollView) {
        //将缩放比例传递给控制器
        photoDelegate?.photoBrowserCellZoom(imageView.transform.a)
    }
}
